import fs from 'fs';
import path from 'path';

// 数据文件路径
const heroesPath = path.join(process.cwd(), 'data', 'heroes.json');
const itemsPath = path.join(process.cwd(), 'data', 'items.json');
const compositionGuidesPath = path.join(process.cwd(), 'data', 'composition_guides.json');

// 英雄数据类型
export interface Skill {
  name: string;
  icon: string;
  description: string;
}

export interface Skin {
  name: string;
  image: string;
}

export interface Hero {
  id: string;
  name: string;
  title: string;
  roles: string[];
  avatar: string;
  skills: Skill[];
  skins: Skin[];
  story: string;
  recommended_builds: string[][];
}

// 装备数据类型
export interface Item {
  id: string;
  name: string;
  type: string;
  price: number;
  icon: string;
  attributes: string[];
  passive_effects: string[];
  build_path?: string[];
  builds_into?: string[];
}

// 阵容搭配指南类型
export interface CompositionGuide {
  id: string;
  name: string;
  description: string;
  roles: string[];
  example_heroes: { role: string; heroes: string[] }[];
  strengths: string[];
  weaknesses: string[];
}

// 获取所有英雄数据
export function getAllHeroes(): Hero[] {
  try {
    const fileContents = fs.readFileSync(heroesPath, 'utf8');
    return JSON.parse(fileContents);
  } catch (error) {
    console.error('Error loading heroes data:', error);
    return [];
  }
}

// 获取单个英雄数据
export function getHeroById(id: string): Hero | undefined {
  const heroes = getAllHeroes();
  return heroes.find(hero => hero.id === id);
}

// 获取所有装备数据
export function getAllItems(): Item[] {
  try {
    const fileContents = fs.readFileSync(itemsPath, 'utf8');
    return JSON.parse(fileContents);
  } catch (error) {
    console.error('Error loading items data:', error);
    return [];
  }
}

// 获取单个装备数据
export function getItemById(id: string): Item | undefined {
  const items = getAllItems();
  return items.find(item => item.id === id);
}

// 获取装备名称
export function getItemName(id: string): string {
  const item = getItemById(id);
  return item ? item.name : id;
}

// 获取所有阵容搭配指南
export function getAllCompositionGuides(): CompositionGuide[] {
  try {
    const fileContents = fs.readFileSync(compositionGuidesPath, 'utf8');
    return JSON.parse(fileContents);
  } catch (error) {
    console.error('Error loading composition guides data:', error);
    return [];
  }
}

// 获取单个阵容搭配指南
export function getCompositionGuideById(id: string): CompositionGuide | undefined {
  const guides = getAllCompositionGuides();
  return guides.find(guide => guide.id === id);
}
